<template>
  <div class="app-container">
    <el-form style="display: flex; justify-content: space-between">
      <el-form-item>
        <span style="font-wight: blod; font-size: 24px"></span>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="handleFirm">我方合同主体公司</el-button>
      </el-form-item>
    </el-form>

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="结算方式" prop="settlementMethod">
        <el-select v-model="queryParams.settlementMethod" placeholder="请选择">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="按时间" :value="1"></el-option>
          <el-option label="按金额" :value="2"></el-option>
          <el-option label="按工程节点" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="60" label="业务员" prop="salesmanUserIds">
        <el-select
          v-model="queryParams.salesmanUserIds"
          placeholder="请输入名称搜索"
        >
          <el-option
            v-for="item in salesmanUserSearchList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label-width="100px"
        label="合同主体公司"
        prop="subjectFirmId"
      >
        <el-select
          v-model="queryParams.subjectFirmId"
          placeholder="请输入名称搜索"
        >
          <el-option
            v-for="item in subjectFirmList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="40" label="ID" prop="id">
        <el-input
          type="number"
          v-model="queryParams.id"
          placeholder="ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customUserName">
        <el-input
          v-model.trim="queryParams.customUserName"
          placeholder="客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="合同编号" prop="projectNo">
        <el-input
          v-model.trim="queryParams.projectNo"
          placeholder="合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:contract:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :height="divHeight"
      v-loading="loading"
      :data="contractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        fixed="left"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column width="55" label="ID" align="center" prop="id" />
      <el-table-column
        label="合同编号"
        align="center"
        prop="projectNo"
        show-overflow-tooltip
      />
      <el-table-column
        label="客户名称"
        align="center"
        prop="customUserName"
        show-overflow-tooltip
      />
      <el-table-column
        label="我方合同主体公司"
        align="center"
        width="140"
        prop="subjectFirmName"
        show-overflow-tooltip
      />

      <el-table-column label="税率" align="center" prop="rate" />
      <el-table-column
        width="200px"
        label="合同起止日期"
        align="center"
        prop="id"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.contractStartTime }} - {{ scope.row.contractEndTime }}
        </template>
      </el-table-column>
      <el-table-column label="结算方式" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.settlementMethod == 1">按时间</span>
          <span v-if="scope.row.settlementMethod == 2">按金额</span>
          <span v-if="scope.row.settlementMethod == 3">按工程节点</span>
        </template>
      </el-table-column>
      <el-table-column label="抵顶比率" align="center" prop="resistance" />
      <el-table-column label="合同状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.terminationStatus == 0">已过期</span>
          <span v-if="scope.row.terminationStatus == 1">生效中</span>
          <span v-if="scope.row.terminationStatus == 2">已终止</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        width="250"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.terminationStatus != 2"
            icon="el-icon-edit"
            @click="handleTj(scope.row)"
            v-hasPermi="['system:contract:edit']"
            >调价管理</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.terminationStatus != 2"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:contract:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:contract:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工程--合同对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="170px"
      >
        <el-card>
          <div slot="header" class="clearfix">
            <span>客户信息</span>
          </div>
          <el-form-item label="客户" prop="customUserId">
            <div style="display: flex; gap: 50px; align-items: center">
              <span v-if="form.customUserName">{{ form.customUserName }}</span>
              <span v-if="form.userProperty">
                <span style="color: #606266">客户类型：</span>
                <span v-if="form.userProperty == 3">企业</span>
                <span v-if="form.userProperty == 4">个人</span>
              </span>
              <span v-if="form.customUserId"
                ><span style="color: #606266">客户ID：</span>
                {{ form.customUserId }}</span
              >
              <el-button type="text" @click="dialogVisible = true">{{
                form.customUserName ? "请重新选择" : "请选择"
              }}</el-button>
            </div>
          </el-form-item>
          <el-form-item
            v-if="form.userProperty == 3"
            :rules="[
              {
                required: true,
                message: '请选择客户合同主体公司',
                trigger: 'change',
              },
            ]"
            label="客户合同主体公司"
            prop="customerCompanyId"
          >
            <el-select
              v-model="form.customerCompanyId"
              placeholder="请选择客户合同主体公司"
            >
              <el-option
                v-for="(item, index) in sysClientContractCompanyList"
                :key="index"
                :label="item.companyName"
                :value="'' + item.clientContractCompanyId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="form.engineeringList && form.engineeringList.length > 0"
            :rules="[
              { required: true, message: '请选择工程', trigger: 'blur' },
            ]"
            label="工程"
            prop="engineeringIds"
          >
            <div>
              <el-button
                @click="getNotSignedList(form.customUserId)"
                type="text"
                size="small"
                >撤回删除</el-button
              >
            </div>
            <el-table style="width: 583px" :data="form.engineeringList">
              <el-table-column prop="projectNo" label="编号" width="150">
              </el-table-column>
              <el-table-column prop="name" label="工程名称" width="150">
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180">
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button
                    @click="handleClick(scope)"
                    type="text"
                    size="small"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-card>

        <el-card style="margin-top: 10px">
          <div slot="header" class="clearfix">
            <span>我方信息</span>
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请选择我司合同主体公司',
                    trigger: 'change',
                  },
                ]"
                label="我司合同主体公司"
                prop="subjectFirmId"
              >
                <div style="display: flex; gap: 20px; align-items: center">
                  <span v-if="form.subjectFirmId">{{
                    form.subjectFirmName
                  }}</span>
                  <el-button type="text" @click="selectFirmVisible = true">{{
                    form.subjectFirmId ? "请重新选择" : "请选择"
                  }}</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请选择我司业务员',
                    trigger: 'change',
                  },
                ]"
                label="我司业务员"
                prop="salesmanUserIds"
              >
                <div style="display: flex; gap: 20px; align-items: center">
                  <span v-if="form.salesmanUserIds">{{
                    form.salesmanUserIdsName
                  }}</span>
                  <el-button type="text" @click="selectNameVisible = true">{{
                    form.salesmanUserIds ? "请重新选择" : "请选择"
                  }}</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card style="margin-top: 10px">
          <div slot="header" class="clearfix">
            <span>合同信息</span>
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请选择合同起止日期',
                    trigger: 'blur',
                  },
                ]"
                label="合同起止日期"
                prop="contractStartTime"
              >
                <el-date-picker
                  v-model="dateArr"
                  type="daterange"
                  range-separator="至"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <NumberFormItem
                errorTip="税率不能为负数"
                label="税率"
                prop="rate"
                requiredMessage="税率"
              >
                <el-input
                  type="number"
                  v-model="form.rate"
                  placeholder="请填写税率"
                />
              </NumberFormItem>
              <!-- <el-form-item
                :rules="[
                  { required: true, message: '请填写税率', trigger: 'blur' },
                ]"
                label="税率"
                prop="rate"
              >
                <el-input
                  type="number"
                  v-model="form.rate"
                  placeholder="请填写税率"
                />
              </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3">
              <el-form-item required label="付款人"></el-form-item>
            </el-col>
            <el-col :span="6" style="margin-left: 56px">
              <el-form-item
                :rules="[
                  { required: true, message: '请填写付款人', trigger: 'blur' },
                ]"
                label-width="0px"
                prop="payerName"
              >
                <el-input v-model="form.payerName" placeholder="请填写姓名" />
              </el-form-item>
            </el-col>
            <el-col style="margin-left: 17px" :span="6">
              <el-form-item
                :rules="[
                  { required: true, message: '请填写手机号', trigger: 'blur' },
                  {
                    validator: validatorPhone,
                    trigger: 'blur',
                  },
                ]"
                label-width="0px"
                prop="payerPhone"
              >
                <el-input
                  v-model="form.payerPhone"
                  placeholder="请填写手机号"
                />
              </el-form-item>
            </el-col>
            <el-col style="margin-left: 17px" :span="6">
              <div style="height: 36px; display: flex; align-items: center">
                <el-link @click="paymentVisible = true" type="primary"
                  >选择历史付款人</el-link
                >
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <NumberFormItem
                errorTip="抵顶比例不能为负数"
                label="抵顶比例"
                prop="resistance"
                requiredMessage="抵顶比例"
              >
                <el-input
                  type="number"
                  v-model="form.resistance"
                  placeholder="请填写抵顶比例"
                />
              </NumberFormItem>
            </el-col>
            <el-col :span="12">
              <NumberFormItem
                errorTip="合同方量不能为负数"
                :required="false"
                label="合同方量"
                prop="contractVolume"
              >
                <el-input
                  type="number"
                  v-model="form.contractVolume"
                  placeholder="请填写合同方量"
                />
              </NumberFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3">
              <el-form-item required label="结算方式"></el-form-item>
            </el-col>
            <el-col style="margin-left: 56px" :span="6">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请选择结算方式',
                    trigger: 'change',
                  },
                ]"
                label-width="0px"
                prop="settlementMethod"
              >
                <el-select v-model="form.settlementMethod" placeholder="请选择">
                  <el-option label="按时间" :value="1"></el-option>
                  <el-option label="按金额" :value="2"></el-option>
                  <el-option label="按工程节点" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              style="margin-left: 17px"
              :span="6"
              v-if="form.settlementMethod == 2"
            >
              <NumberFormItem
                requiredMessage="单次结算金额"
                errorTip="单次结算金额不能为负数"
                labelWidth="0px"
                prop="settlementAmount"
              >
                <el-input
                  type="number"
                  v-model="form.settlementAmount"
                  placeholder="单次结算金额"
                />
              </NumberFormItem>
            </el-col>
          </el-row>
          <el-form-item
            :rules="[
              { required: true, message: '请上传附件', trigger: 'change' },
            ]"
            label="合同附件"
            prop="annex"
          >
            <FileUpload
              :fileType="['jpg', 'jpeg', 'pdf', 'doc', 'docx', 'xlsx', 'xls']"
              v-model="form.annex"
              :limit="1"
            />
          </el-form-item>
        </el-card>

        <el-card style="margin-top: 10px">
          <div slot="header" class="clearfix">
            <span>合同价格信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <NumberFormItem
                errorTip="单价不能为负数"
                requiredMessage="冬施每方单价"
                label="缺省泵送每方单价(元)"
                prop="pumpingPrice"
              >
                <el-input
                  type="number"
                  v-model="form.pumpingPrice"
                  placeholder="请填写"
                />
              </NumberFormItem>
            </el-col>
            <el-col :span="8">
              <NumberFormItem
                requiredMessage="冬施每方单价"
                errorTip="单价不能为负数"
                label="冬施每方单价(元)"
                prop="winterPrice"
              >
                <el-input
                  type="number"
                  v-model="form.winterPrice"
                  placeholder="请填写"
                />
              </NumberFormItem>
            </el-col>
            <el-col style="margin-left: 50px" v-if="!form.id" :span="4">
              <div style="height: 36px; display: flex; align-items: center">
                <el-link @click="selectContractVisible = true" type="primary"
                  >复制其他合同价格</el-link
                >
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="23" style="padding-left: 23px">
            <el-col :span="12">
              <el-form-item
                label-width="0px"
                :rules="[
                  {
                    required: true,
                    message: '请添加主标号',
                    trigger: 'change',
                  },
                ]"
                label=" "
                prop="primaryDesignatorList"
              >
                <div>
                  <el-button @click="addMain" type="text" size="small"
                    >添加主标号</el-button
                  >
                  <el-table
                    :data="form.primaryDesignatorList"
                    size="mini"
                    height="200"
                  >
                    <el-table-column
                      prop="primaryDesignatorName"
                      label="主标号名称"
                      width="150"
                    >
                    </el-table-column>
                    <el-table-column prop="price" label="单价" width="150">
                      <template slot-scope="scope">
                        <div>
                          <NumberFormItem
                            errorTip="单价不能为负数"
                            labelWidth="0px"
                            v-if="!scope.row.disabled"
                            :prop="
                              'primaryDesignatorList[' +
                              scope.$index +
                              '].price'
                            "
                          >
                            <el-input
                              size="mini"
                              type="number"
                              v-model="scope.row.price"
                              placeholder="请输入单价"
                            />
                          </NumberFormItem>
                          <span v-else> {{ scope.row.price }} </span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                      <template slot-scope="scope">
                        <el-button
                          :disabled="scope.row.disabled"
                          @click="removeMain(scope)"
                          type="text"
                          size="small"
                          >移除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label-width="0px"
                :rules="[
                  {
                    required: true,
                    message: '请添加附加标号',
                    trigger: 'change',
                  },
                ]"
                label=" "
                prop="additionalTitleList"
              >
                <div>
                  <el-button
                    @click="selectSubMainVisible = true"
                    type="text"
                    size="small"
                    >添加附加标号</el-button
                  >
                  <el-table
                    :data="form.additionalTitleList"
                    size="mini"
                    height="200"
                  >
                    <el-table-column
                      prop="additionalTitleName"
                      label="附加标号名称"
                      width="150"
                    >
                    </el-table-column>
                    <el-table-column prop="price" label="单价" width="150">
                      <template slot-scope="scope">
                        <div>
                          <NumberFormItem
                            v-if="!scope.row.disabled"
                            errorTip="单价不能为负数"
                            labelWidth="0px"
                            :prop="
                              'additionalTitleList[' + scope.$index + '].price'
                            "
                          >
                            <el-input
                              size="mini"
                              type="number"
                              v-model="scope.row.price"
                              placeholder="请输入单价"
                            />
                          </NumberFormItem>
                          <span v-else> {{ scope.row.price }} </span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                      <template slot-scope="scope">
                        <el-button
                          :disabled="scope.row.disabled"
                          @click="removeSubMain(scope)"
                          type="text"
                          size="small"
                          >移除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="23" style="padding-left: 23px">
            <el-col :span="12">
              <el-form-item
                label-width="0px"
                :rules="[
                  {
                    required: true,
                    message: '请添加服务加价',
                    trigger: 'change',
                  },
                ]"
                label=" "
                prop="markupsConfigList"
              >
                <div>
                  <el-button
                    @click="selectServiceVisible = true"
                    type="text"
                    size="small"
                    >添加服务加价</el-button
                  >
                  <el-table
                    :data="form.markupsConfigList"
                    size="mini"
                    height="200"
                  >
                    <el-table-column
                      prop="markupsName"
                      label="加价名称"
                      width="120"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="markupsType"
                      label="计价类型"
                      width="120"
                    >
                      <template slot-scope="scope">
                        <span v-if="scope.row.markupsType == 1">一口价</span>
                        <span v-else>单价</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="price" label="单价">
                      <template slot-scope="scope">
                        <div>
                          <NumberFormItem
                            v-if="!scope.row.disabled"
                            errorTip="单价不能为负数"
                            labelWidth="0px"
                            :prop="
                              'markupsConfigList[' + scope.$index + '].price'
                            "
                          >
                            <el-input
                              size="mini"
                              type="number"
                              v-model="scope.row.price"
                              placeholder="请输入单价"
                            />
                          </NumberFormItem>
                          <span v-else> {{ scope.row.price }} </span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template slot-scope="scope">
                        <el-button
                          :disabled="scope.row.disabled"
                          @click="removeService(scope)"
                          type="text"
                          size="small"
                          >移除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card style="margin-top: 10px">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" v-if="form.id" @click="endContract"
          >终止合同</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectCustomDialog
      :queryExtraParams="{
        orderBy:'desc'
      }"
      :multiple="false"
      :dialogVisible="dialogVisible"
      @onClose="dialogVisible = false"
      @onSubmit="handleOnSubmit"
    ></SelectCustomDialog>
    <SelectSalesmanDialog
      :styleOptions="{
        btnAlign: true,
        inputStyle: {
          width: '240px',
        },
        labelWidth: ' ',
      }"
      :dialogVisible="selectNameVisible"
      :defauleUser="defauleUser"
      :disabledSearchFieldList="['principalPhone']"
      @onClose="selectNameVisible = false"
      @onSubmit="selectName"
    ></SelectSalesmanDialog>
    <SelectFirmDialog
      :dialogVisible="selectFirmVisible"
      @onClose="selectFirmVisible = false"
      @onSubmit="selectFirm"
    ></SelectFirmDialog>
    <SelectPaymentDialog
      :dialogVisible="paymentVisible"
      @onClose="paymentVisible = false"
      @onSubmit="handleOnPaymentSubmit"
    ></SelectPaymentDialog>
    <SelectMainDialog
      :dialogVisible="selectMainVisible"
      @onClose="selectMainVisible = false"
      :multiple="false"
      :disableIds="
        (form.primaryDesignatorList || []).map(
          (item) => item.primaryDesignatorId
        )
      "
      @onSubmit="handleOnMainSubmit"
    ></SelectMainDialog>
    <SelectSubMainDialog
      :dialogVisible="selectSubMainVisible"
      @onClose="selectSubMainVisible = false"
      :multiple="false"
      :disableIds="
        (form.additionalTitleList || []).map((item) => item.additionalTitleId)
      "
      @onSubmit="handleOnSubMainSubmit"
    ></SelectSubMainDialog>
    <SelectServiceDialog
      :dialogVisible="selectServiceVisible"
      @onClose="selectServiceVisible = false"
      :disableIds="
        (form.markupsConfigList || []).map((item) => item.markupsConfigId)
      "
      @onSubmit="handleOnServiceSubmit"
    ></SelectServiceDialog>
    <SelectContractDialog
      :dialogVisible="selectContractVisible"
      @onClose="selectContractVisible = false"
      :multiple="false"
      @onSubmit="handleOnContractSubmit"
    ></SelectContractDialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import { getInfo } from "@/api/system/info";
import { listFirm } from "@/api/service/marketing/firm";
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
  notSignedList,
} from "@/api/service/marketing/contract";
import SelectCustomDialog from "@/components/SelectDialog/SelectCustomDialog";
import SelectNameDialog from "@/components/SelectDialog/SelectNameDialog";
import SelectFirmDialog from "@/components/SelectDialog/SelectFirmDialog";
import SelectPaymentDialog from "@/components/SelectDialog/SelectPaymentDialog";
import SelectMainDialog from "@/components/SelectDialog/SelectMainDialog";
import SelectSubMainDialog from "@/components/SelectDialog/SelectSubMainDialog";
import SelectServiceDialog from "@/components/SelectDialog/SelectServiceDialog";
import SelectSalesmanDialog from "@/components/SelectDialog/SelectSalesmanDialog";
import SelectContractDialog from "@/components/SelectDialog/SelectContractDialog";
import { isArray, isValidPhoneNumber } from "@/utils/validate";
import NumberFormItem from "@/components/NumberFormItem";
export default {
  components: {
    NumberFormItem,
    SelectSalesmanDialog,
    SelectMainDialog,
    SelectPaymentDialog,
    SelectCustomDialog,
    SelectNameDialog,
    SelectFirmDialog,
    SelectSubMainDialog,
    SelectServiceDialog,
    SelectContractDialog,
  },
  name: "Contract",
  data() {
    const validatorPhone = (rule, value, callback) => {
      if (value) {
        if (!isValidPhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      divHeight:500,
      validatorPhone,
      selectContractVisible: false,
      selectServiceVisible: false,
      selectSubMainVisible: false,
      selectMainVisible: false,
      paymentVisible: false,
      selectFirmVisible: false,
      selectNameVisible: false,
      dialogVisible: false,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程--合同表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        settlementMethod: null,
        customUserName: null,
        salesmanUserIds: null,
        subjectFirmId: null,
        id: null,
        projectNo: null,
      },
      // 远程搜索业务员结果
      salesmanUserLoading: false,
      salesmanUserSearchList: [],
      // 合同公司搜索结果
      subjectFirmLoading: false,
      subjectFirmList: [],
      // 表单参数
      form: {
        customUserId: "",
        markupsConfigList: [],
      },
      // 表单校验
      rules: {
        customUserId: [
          { required: true, message: "请选择客户", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请选择客户"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },

      sysClientContractCompanyList: [],
    };
  },
  computed: {
    defauleUser() {
      if (this.form.salesmanUserIds) {
        const ids = this.form.salesmanUserIds.split(",");
        const names = this.form.salesmanUserIdsName.split(",");
        return ids.map((id, index) => ({ userId: id, nickName: names[index] }));
      } else {
        return [];
      }
    },
    dateArr: {
      get() {
        if (this.form?.contractStartTime) {
          return [this.form?.contractStartTime, this.form?.contractEndTime];
        }
        return [];
      },
      set(value) {
        this.form.contractStartTime = value[0];
        this.form.contractEndTime = value[1];
      },
    },
  },
  mounted() {
    
  },
  created() {
    this.divHeight = window.innerHeight -400;
    this.getList();
    this.subjectFirmRemoteMethod()
    this.remoteMethod()
  },
  watch: {
    "form.customUserId": {
      handler(id) {
        if (id) {
          this.getCustomerCompanyList(id);
          if (!this.form.id) {
            this.getNotSignedList(id);
          }
        } else {
          this.sysClientContractCompanyList = [];
        }
      },
    },
  },
  methods: {
    handleFirm() {
      this.$router.push({
        path: "/marketing/firm",
      });
    },
    async subjectFirmRemoteMethod(query) {
      // this.queryParams.subjectFirmId = null
      // if (query !== "") {
        // this.subjectFirmLoading = true;
        const res = await listFirm({
          name: query,
          pageNum: 1,
          // pageSize: ,
        });
        // this.subjectFirmLoading = false;
        this.subjectFirmList = res.rows;
      // } else {
      //   this.subjectFirmList = [];
      // }
    },
    async remoteMethod(query) {
      // this.queryParams.salesmanUserIds = null
      // if (query !== "") {
      //   this.subjectFirmLoading = true;
        const res = await listUser({
          userType: 1,
          roleCodeList: "business_role",
          nickName: query,
          pageNum: 1,
          // pageSize: 5,
        });
        // this.subjectFirmLoading = false;
        this.salesmanUserSearchList = res.rows;
      // } else {
      //   this.salesmanUserSearchList = [];
      // }
    },
    removeMain(scope) {
      this.form.primaryDesignatorList.splice(scope.$index, 1);
    },
    removeService(scope) {
      this.form.markupsConfigList.splice(scope.$index, 1);
    },
    removeSubMain(scope) {
      this.form.additionalTitleList.splice(scope.$index, 1);
    },
    selectQuerySalesman(row) {
      console.log(row);
    },
    handleOnContractSubmit(row) {
      this.form.pumpingPrice = row.pumpingPrice;
      this.form.winterPrice = row.winterPrice;
    },
    handleOnSubMainSubmit(row) {
      this.form.additionalTitleList.push({
        disabled: false,
        additionalTitleId: row.id,
        additionalTitleName: row.name,
        price: row.price,
        valuationType: 2,
      });
      this.$refs.form.validateField("additionalTitleList");
    },

    handleOnMainSubmit(row) {
      this.form.primaryDesignatorList.push({
        disabled: false,
        primaryDesignatorId: row.id,
        primaryDesignatorName: row.name,
        price: row.benchmarkPrice,
        valuationType: 2,
      });
      this.$refs.form.validateField("primaryDesignatorList");
    },
    addMain() {
      this.selectMainVisible = true;
      //this.form.primaryDesignatorList.push()
    },
    handleOnPaymentSubmit(row) {
      this.form.payerName = row.name;
      this.form.payerPhone = row.phone;
      this.$refs.form.validateField("payerName");
      this.$refs.form.validateField("payerPhone");
    },
    handleOnServiceSubmit(row) {
      this.form.markupsConfigList.push({
        disabled: false,
        markupsConfigId: row.id,
        markupsName: row.markupsName,
        markupsType: row.markupsType.includes("一口价") ? 2 : 1,
        price: row.markupsValue,
      });
      this.$refs.form.validateField("markupsConfigList");
    },
    selectFirm(row) {
      this.form.subjectFirmId = row.id;
      this.form.subjectFirmName = row.name;
      this.$refs.form.validateField("subjectFirmId");
    },
    selectName(arr) {
      this.form.salesmanUserIds = arr.map((item) => item.userId).join(",");
      this.form.salesmanUserIdsName = arr
        .map((item) => item.nickName)
        .join(",");
      this.$refs.form.validateField("salesmanUserIds");
    },
    handleClick(scope) {
      if (this.form.engineeringList.length == 1) {
        this.$message({
          message: "至少选择一个工程",
          type: "warning",
        });
        return;
      }
      this.form.engineeringList.splice(scope.$index, 1);
    },
    // 获取客户未关联合同的工程
    async getNotSignedList(customUserId) {
      const res = await notSignedList({ customUserId });
      if (res.data && res.data.length == 0) {
        this.$message({
          message: "该客户暂无未关联合同的工程",
          type: "warning",
        });
      }
      []
      this.form.engineeringList = res.data.filter((item) => {
        return !item.contract
      });
    },
    async getCustomerCompanyList(id) {
      const res = await getInfo(id);
      this.sysClientContractCompanyList = res.data.sysClientContractCompanyList;
    },
    handleOnSubmit(row) {
      this.form.customUserId = row.userInfoId;
      this.form.customUserName = row.principalName;
      this.form.userProperty = row.userProperty;
      this.$refs.form.validateField("customUserId");
    },
    /** 查询工程--合同列表 */
    getList() {
      this.loading = true;

      listContract({
        ...this.queryParams,
        // salesmanUserIds: (this.queryParams.salesmanUserIds || []).join(","),
      }).then((response) => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customUserName: null,
        customUserId: null,
        userProperty: null,
        customerCompanyId: null,
        engineeringIds: null,
        engineeringList: [],
        primaryDesignatorList: [],
        additionalTitleList: [],
        markupsConfigList: [],
        salesmanUserIdsName: null,
        subjectFirmId: null,
        salesmanUserIds: null,
        subjectFirmName: null,
        contractStartTime: null,
        contractEndTime: null,
        rate: null,
        payerName: null,
        payerPhone: null,
        resistance: null,
        contractVolume: null,
        settlementMethod: null,
        settlementAmount: null,
        annex: null,
        pumpingPrice: null,
        winterPrice: null,
        code: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增合同";
    },
    handleTj(row) {
      this.$router.push({
        path:
          "/marketing/priceAdjustmentManagement?id=" +
          row.id +
          "&name=" +
          (row.customUserName ? row.customUserName : ""),
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getContract(id).then((response) => {
        this.form = {
          ...response.data,
          primaryDesignatorList: (
            response.data.primaryDesignatorList || []
          ).map((item) => ({ ...item, disabled: true })),
          additionalTitleList: (response.data.additionalTitleList || []).map(
            (item) => ({ ...item, disabled: true })
          ),
          markupsConfigList: (response.data.markupsConfigList || []).map(
            (item) => ({ ...item, disabled: true })
          ),
          salesmanUserIdsName: (response.data.salesmanUserList || [])
            .map((item) => item.nickName)
            .join(","),
        };
        this.open = true;
        this.title = "修改合同";
      });
    },
    // 终止合同
    async endContract() {
      await this.$modal.confirm("确定要终止合同吗？");
      updateContract({
        id: this.form.id,
        terminationStatus: 2,
      }).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.engineeringIds = this.form.engineeringList
        .map((item) => item.id)
        .join(",");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (!this.form.engineeringIds) {
              return this.$modal.msgError("该客户暂无未关联合同的工程，不可新增");
            }
            addContract(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除工程--合同编号为"' + ids + '"的数据项？')
        .then(function () {
          return delContract(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/contract/export",
        {
          ...this.queryParams,
        },
        `contract_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container{
  overflow: hidden;
}
::v-deep .el-tabs__content {
  max-height: 500px;
  overflow: auto;
}
::v-deep .el-dialog__body {
  max-height: 700px;
  overflow: auto;
}
</style>